package com.deepocean.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MessageSourceUtil {
    @Value("spring.messages.basename")
    private String basename;
    @Value("spring.messages.encoding")
    private String encoding;
    @Autowired
    LanguageUtil languageUtil;

    private static MessageSource messageSource;

    private ReloadableResourceBundleMessageSource bundleMessageSource = new ReloadableResourceBundleMessageSource();

    @PostConstruct
    public void initMessageSource() {
        bundleMessageSource.setBasename(basename);
        bundleMessageSource.setDefaultEncoding(encoding);
        setMessageSource(bundleMessageSource);
    }

    private static void setMessageSource (ReloadableResourceBundleMessageSource bundleMessageSource) {
        messageSource = bundleMessageSource;
    }

    public String getMessage(String key) {
        return messageSource.getMessage(key, null, languageUtil.getLocale());
    }
}
